#*-* coding:utf-8 *-*
from mongoengine import *

class Mongo(object):
    def __init__(self,database,collection,**fields):
        self.db=database
        self.doc_fields=fields
        self.col=type(collection,(Document,),fields)
        connect(self.db)
    def findall(self,**kwargs):
        res=[]
        obj=self.col.objects(kwargs)
        for i in range(len(obj)):
            res.append({})
            for j in self.doc_fields["_db_field_map"]:
                if j=="id":continue
                res[i][j]=eval("obj[i].%s"%j)
        return res
    def insert(self,**kwargs):
        the=self.col()
        for i in kwargs:
            exec("the.%s=kwargs['%s']"%(i,i))
        the.save()
    def update(self,contents,**kwargs):
        the = self.col
        res = the.objects(**kwargs)
        for i in res:
            for key in contents:
                exec('i.%s=contents["%s"]'%(key,key))
            i.save()
    def remove(self,**kwargs):
        the=self.col
        res=the.objects(**kwargs)
        for i in res:
            i.delete()

def main(mode="findall"):
    collection_word={
                    "word":StringField(),
                    "meaning":StringField()
                    }
    a=Mongo("English","word",**collection_word)
    if mode=="findall":
        for i in a.findall():
            for j in i:
                print j+":"+i[j]

    elif mode=="insert":
        a.insert(word="three", meaning="三")
    elif mode=="remove":
        a.remove(word="two")
    elif mode=="update":
        a.update({"meaning":"二，二个","word":"two"},word="three")
    else:
        print 'mode`s setting is wrong,must be in ["findall","insert","remove","update"]\n'

if __name__=="__main__":
    #a.insert(word="two",meaning="二")
    main("update")
    main("findall")





